package com.sky.utils;

import com.alibaba.fastjson.JSONObject;
import com.sky.properties.BaiduProperties;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Map;

@Component
public class BaiduUtil {
    @Autowired
    private BaiduProperties baiduProperties;

    public JSONObject doGet(String strUrl, Map<String, String> param) throws Exception {
        param.put("ak", baiduProperties.getAk());
        param.put("output", "json");
        // 创建 URI Builder
        URIBuilder builder = new URIBuilder(strUrl);
        // 将参数添加到 URI 中
        for (Map.Entry<String, String> entry : param.entrySet()) {
            builder.setParameter(entry.getKey(), entry.getValue());
        }
        CloseableHttpClient httpClient = HttpClients.createDefault();
        HttpGet httpGet = new HttpGet(builder.build());
        CloseableHttpResponse response = httpClient.execute(httpGet);
        int statusCode = response.getStatusLine().getStatusCode();
        System.out.println("statusCode = " + statusCode);
        HttpEntity entity = response.getEntity();
        String json = EntityUtils.toString(entity);
        System.out.println("string = " + json);
        return JSONObject.parseObject(json);
    }
}
